package summary;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/7/8 10:29
 * https://leetcode.cn/problems/pacific-atlantic-water-flow/
 */
public class Title417II {

    int n, m;

    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        n = heights.length;
        m = heights[0].length;
        int[][] pOcean = new int[n][m];
        int[][] aOcean = new int[n][m];
        for (int i = 0; i < n; i++) {
            dfs(heights, pOcean, i, 0, -1);
            dfs(heights, aOcean, i, m - 1, -1);
        }
        for (int j = 0; j < m; j++) {
            dfs(heights, pOcean, 0, j, -1);
            dfs(heights, aOcean, n - 1, j, -1);
        }
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (pOcean[i][j] == 1 && aOcean[i][j] == 1) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(i);
                    temp.add(j);
                    result.add(temp);
                }
            }
        }
        return result;
    }

    private void dfs(int[][] heights, int[][] ocean, int i, int j, int pre) {
        if (i < 0 || i >= n || j < 0 || j >= m || ocean[i][j] == 1 || heights[i][j] < pre) {
            return;
        }
        ocean[i][j] = 1;
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        for (int k = 0; k < 4; k++) {
            dfs(heights, ocean, i + dx[k], j + dy[k], heights[i][j]);
        }
    }

    public static void main(String[] args) {

    }
}
